package service.impl;

import Dao.BookDao;
import Dao.impl.BookDaoImpl;
import pojo.Book;
import pojo.Page;
import service.BookService;

import java.util.List;
public class BookServiceImpl implements BookService {
    private  BookDao booker = new BookDaoImpl();
    @Override
    public void addBook(Book book) {
        booker.addBook(book);
    }

    @Override
    public void deleteBookyById(Integer id) {
        booker.deleteBookById(id);
    }

    @Override
    public void updateBook(Book book) {
        booker.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        return booker.queryBookById(id);
    }

    @Override
    public List<Book> queryAllBook() {
        return booker.queryAllBook();
    }

    @Override
    public Page<Book> page(int pageNo, int pageSize,String url) {
        //创建page对象
        Page<Book>page = new Page<Book>();
        //设置要转发到那个url中的servlet程序
        page.setUrl(url);
        //设计每页数量
        page.setPageSize(pageSize);
        //获取总记录数 即总共多少本书
        Long i = booker.queryForPageTotalCount();
        //设置总记录数 即总共多少本书
        page.setGetTotalCount(i);
        //获取总页码
        Long total = i/pageSize;
        if(i%pageSize>0){
            total++;
        }
        //设置总页码
        page.setPageTotal(total);
        //数据边界的有效检查
        if(pageNo<1){
            pageNo=1;
        }else if(pageNo>total){
            pageNo= Math.toIntExact(total);
        }
        page.setPageNo(pageNo);
        //分页查询的begin
        int begin = (page.getPageNo()-1)*pageSize;
        //分页查询完后返回来的对象
        List<Book> books = booker.queryForitems(begin, pageSize);
        //将这个对象保存在page中的list对象中
        page.setItems(books);

        return page;
    }

    @Override
    public Page<Book> pageByPrice(int pageNo, int pageSize, int min, int max,String url) {
        Page<Book>page = new Page<Book>();
        page.setUrl(url);
        page.setPageSize(pageSize);
        Long i = booker.queryForPageTotalCount(min,max);
        page.setGetTotalCount(i);
        Long total = i/pageSize;
        if(i%pageSize>0){
            total++;
        }
        page.setPageTotal(total);
        //数据边界的有效检查
        if(pageNo<1){
            pageNo=1;
        }else if(pageNo>total){
            pageNo= Math.toIntExact(total);
        }
        page.setPageNo(pageNo);

        int begin = (page.getPageNo()-1)*pageSize;
        System.out.println(begin);
        List<Book> books = booker.qurtyForPageItems(begin, pageSize,min,max);
        page.setItems(books);

        return page;
    }
}
